package com.hassean.we.admin.common.Interceptor;

import com.hassean.we.admin.model.entity.TbLog;
import com.hassean.we.admin.service.TbLogService;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.util.URLUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
     * 异常拦截器
     *
     * @author   yajun
     * @create    2019年4月25日
     */
    @Component
    @ControllerAdvice
    public class ExceptionInterceptor implements HandlerInterceptor {
    @Autowired
    private TbLogService tbLogService;

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            //System.out.println(">>>MyInterceptor2>>>>>>>在请求处理之前进行调用（Controller方法调用之前）");

            return true;// 只有返回true才会继续向下执行，返回false取消当前请求
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                               ModelAndView modelAndView) throws Exception {
            //System.out.println(">>>MyInterceptor2>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
        }
        TbLog tbLog = new TbLog();
        String exception =null;
        String type ="0";//0正常，1不正常
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                throws Exception {


            //System.out.println(">>>MyInterceptor2>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
            String requestUri = request.getRequestURI();
            String method = request.getMethod();

            tbLog.setType(type);
            tbLog.setRemoteAddr(HttpUtil.getClientIP(request));
            String url = URLUtil.getPath(requestUri);

            tbLog.setMethod(method);
            tbLog.setUserAgent(request.getHeader("user-agent"));
            tbLog.setParams(HttpUtil.toParams(request.getParameterMap()));

            Long  addTime =new Date().getTime();
            Long startTime  = System.currentTimeMillis() - addTime;;
            tbLog.setTime(startTime.toString());
            String username =  request.getParameter("username");
            tbLog.setCreateBy(username);
            //保存日志
            Boolean flag = true;
            //System.out.println("exception:"+exception);
            if(url.contains("page")){
                flag = false;
            }else{
                tbLog.setRequestUri(URLUtil.getPath(requestUri));
            }
            if(url.contains("add")){
                tbLog.setTitle("添加");
            }else{
                tbLog.setRequestUri(URLUtil.getPath(requestUri));
            }
            if(method.contains("put")||method.contains("PUT")){
                tbLog.setTitle("修改");
            }
            if(method.contains("DELETE")){
                tbLog.setTitle("删除");
            }
            if(url.contains("updateBatch/registration")){
                tbLog.setTitle("批量实名认证更新");
            }
            if(url.contains("tbTerminal/tbTerminalList")){
                tbLog.setTitle("获取终端所有信息列表");
            }
            if(url.contains("file/edit/data")){
                tbLog.setTitle("导入表批量添加");
            }
            if(url.contains("download/data")){
                tbLog.setTitle("导出报表");
            }
            if(url.contains("download/data")){
                tbLog.setTitle("导出报表");
            }
            if(url.contains("tbMessage/add")){
                tbLog.setTitle("发短信");
            }
            if(url.contains("tbMessage/add")){
                tbLog.setTitle("短信群发");
            }
            if(url.contains("tbTerminalTrajectory/getTrajectory")){
                tbLog.setTitle("终端轨迹历史");
            }
            if(url.contains("HttpClientController/getRegistration")){
                tbLog.setTitle("实名制查询");
            }
            if(url.contains("HttpClientController/simFlowOffAndON")){
                tbLog.setTitle("天通卡流量开关");
            }
            if(url.contains("HttpClientController/simFlowOffAndON")){
                tbLog.setTitle("天通卡流量开关");
            }



            tbLog.setException(exception);
            if (flag){
                tbLogService.insert(tbLog);
            }

            exception =null;
            type ="0";
        }

    //全局捕获异常
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Map<String,Object> resultError(RuntimeException runtimeException ){
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("message",runtimeException.getMessage());
        resultMap.put("cause",runtimeException.getCause());
        if(runtimeException.getClass().getName()!=null){
            exception = runtimeException.getClass().getName();
            type = "1";
            resultMap.put("exception",runtimeException.getClass().getName());
            tbLog.setException(runtimeException.getClass().getName());

        }
        return resultMap;
    }

    }

